//
//  ProductDetailVC.m
//  YangWifi
//
//  Created by zuoxueliangduyuanzhuo on 2017/6/20.
//  Copyright © 2017年 zuoxueliangduyuanzhuo. All rights reserved.
//

#import "ProductDetailVC.h"
#import "PayWayBottomV.h"
#import "ProductInfoCell.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "WXApiManager.h"

@interface ProductDetailVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,weak) IBOutlet PayWayBottomV *payV;

@property (nonatomic ,weak) IBOutlet UITableView *tableV;

@property (nonatomic ,strong) NSMutableArray *data;


@end

@implementation ProductDetailVC

- (void)loadView
{
    [super loadView];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"产品详情";
    
    self.tableV.estimatedRowHeight = 100;
    self.tableV.rowHeight = UITableViewAutomaticDimension;
    
    self.payV.PayWayChooseHandler = ^(PayWayType type) {
        DLog(@"%ld",type);
        if (type == PayWayTypeAli) {
            [self aliPayRequest];
        }else{
            [self wechatRequest];
        }
    
    };
    self.tableV.separatorColor = [UIColor clearColor];
    [self.tableV registerNib:[UINib nibWithNibName:@"ProductInfoCell" bundle:nil] forCellReuseIdentifier:@"ProductInfoCell"];
    
    self.tableV.tableFooterView = [[UIView alloc] init];
    self.tableV.tableHeaderView = [[UIView alloc] init];
    
    [self.data addObject:@{@"title":@"套餐类型",
                           @"content":self.infoData.packageName,
                           }];
    [self.data addObject:@{@"title":@"套餐内容",
                           @"content":self.infoData.packageContent,
                           }];
//    [self.data addObject:@{@"title":@"激活时间",
//                           @"content":@"2017年3月15日 - 2017年4月15日",
//                           }];
    [self.data addObject:@{@"title":@"服务价格",
                           @"content":self.infoData.packagePrice,
                           }];
    [self.data addObject:@{@"title":@"套餐试用范围说明",
                           @"content":self.infoData.remark,
                           }];
}


- (void)wechatRequest
{
    NSDictionary *params = @{@"type":@"OSWIFI_PACKAGEDETAIL_MOBILE",
                             @"token":[AccountHanler token],
                             @"requestEntity":@{
                                     @"order_no":IsNull(self.orderData.id, @""),
                                     @"packageId":IsNull(self.infoData.id, @""),
                                     @"telephone":[AccountHanler telPhone]}
                             };
    @WeakObj(self);
    [MHNetworkManager postReqeustWithURL:nil params:params successBlock:^(NSDictionary *returnData) {
        
        XLBaseModel *resultData = [XLBaseModel mj_objectWithKeyValues:returnData];
        if (resultData.resultFlag) {
            
            [self wechatPay:resultData.responseEntity[0]];
            
        }else{
            
            [Weakself.view makeToast:@"生成订单失败"];
        }
        
    } failureBlock:^(NSError *error) {
        
        [Weakself.view makeToast:@"生成订单失败"];
        
    } showHUD:YES];
}

- (void)aliPayRequest
{
    NSDictionary *params = @{@"type":@"OSWIFI_ALIPAY_PAYMENTORDERINFO",
                             @"token":[AccountHanler token],
                             @"requestEntity":@{
                                     @"order_no":IsNull(self.orderData.id, @""),
                                     @"packageId":IsNull(self.infoData.id, @""),
                                     @"telephone":[AccountHanler telPhone]}
                             };
    @WeakObj(self);
    [MHNetworkManager postReqeustWithURL:nil params:params successBlock:^(NSDictionary *returnData) {
        
        XLBaseModel *resultData = [XLBaseModel mj_objectWithKeyValues:returnData];
        if (resultData.resultFlag) {
            
            [self aliPay:resultData.responseEntity[0][@"data"]];
            
        }else{
            
            [Weakself.view makeToast:@"生成订单失败"];
        }
        
    } failureBlock:^(NSError *error) {
        
        [Weakself.view makeToast:@"生成订单失败"];
    
    } showHUD:YES];
}


- (void)aliPay:(NSString *)authInfoStr
{
    [[AlipaySDK defaultService] auth_V2WithInfo:authInfoStr
                                     fromScheme:aliPayScheme
                                       callback:^(NSDictionary *resultDic) {
                                           NSLog(@"result = %@",resultDic);
                                           // 解析 auth code
                                           NSString *result = resultDic[@"result"];
                                           NSString *authCode = nil;
                                           if (result.length>0) {
                                               NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                                               for (NSString *subResult in resultArr) {
                                                   if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                                                       authCode = [subResult substringFromIndex:10];
                                                       break;
                                                   }
                                               }
                                           }
                                           NSLog(@"授权结果 authCode = %@", authCode?:@"");
                                       }];

}

- (void)wechatPay:(NSDictionary *)payDic
{
    
    if (IsNil(payDic[@"partnerid"])||
        IsNil(payDic[@"prepayid"])||
        IsNil(payDic[@"noncestr"])||
        IsNil(payDic[@"timestamp"])||
        IsNil(payDic[@"package"])||
        IsNil(payDic[@"sign"])) {

    }else{
        //调起微信支付
        PayReq* req             = [[PayReq alloc] init];
        req.partnerId           = [payDic objectForKey:@"partnerid"];
        req.prepayId            = [payDic objectForKey:@"prepayid"];
        req.nonceStr            = [payDic objectForKey:@"noncestr"];
        req.timeStamp           = [[payDic objectForKey:@"timestamp"] intValue];
        req.package             = [payDic objectForKey:@"package"];
        req.sign                = [payDic objectForKey:@"sign"];
        [WXApi sendReq:req];
    }
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"ProductInfoCell";
    ProductInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.titleL.text = self.data[indexPath.row][@"title"];
    cell.contentL.text = self.data[indexPath.row][@"content"];
    if (indexPath.row == self.data.count-1) {
        cell.lineV.hidden = YES;
    }else{
        cell.lineV.hidden = NO;
    }

    return cell;
}

- (NSMutableArray *)data{
    if (!_data) {
        _data = [NSMutableArray arrayWithCapacity:0];
    }
    return _data;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
